import Vue from 'vue'
import Vuex from 'vuex'
import axios from '../axios'
import {
    SA_TOKEN_NAME,
    TOKEN_KEY
} from "../constant/system"

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        user: window.sessionStorage.getItem('loginUser'),
        token: window.sessionStorage.getItem(TOKEN_KEY) || '',
        menus: [],
        selectItem:window.sessionStorage.getItem("selectItem"),
        isProduct: 1
    },
    getters: {
        menus: state => {
            return state.menus
        },
        user: state => {
            return state.user
        },
        token: state => {
            return state.token
        },
        isProduct: state => {
            let isProduct = parseInt(window.sessionStorage.getItem("isProduct"));
            if (isProduct){
                state.isProduct = isProduct;
            }
            return state.isProduct;
        }

    },
    mutations: {
        SET_USER: (state, user) => {
            state.user = user
            window.sessionStorage.setItem("loginUser", JSON.stringify(user))
        },

        SET_TOKEN: (state, token) => {
            state.token = token
            window.sessionStorage.setItem(TOKEN_KEY, token)
        },
        SET_MENU: (state, menus) => {
            state.menus = menus
        },
        RESET_STATE(state) {
            state.menus = []
            state.user = null
            state.token = ""
            state.isProduct = 0
			window.sessionStorage.removeItem(TOKEN_KEY)
        },
        SET_PRODUCT: (state,isProduct) =>{
            state.isProduct = isProduct;
            window.sessionStorage.setItem("isProduct",isProduct);
        }

    },
    actions: {
        // 获取路由菜单
        GENERATE_ROUTES({commit}) {
            return new Promise(resolve => {
                console.log("【菜单】获取菜单路由")
                axios.get('/sysMenu/menuRoute').then(resp => {
                    if (resp.status) {
                        var menuRoutes = formatRoutes(resp.data[0].children)
                        commit('SET_MENU', menuRoutes)
                        resolve(menuRoutes)
                    }
                })
            })
        },
        // 退出登录
        CLEAR_LOGIN_INFO({commit}) {
            commit("RESET_STATE")
        }
    }
})



const formatRoutes = (routes) => {

    let fmtRoutes = []
    routes.forEach(route => {
        if (route.children) {
            route.children = formatRoutes(route.children)
        }

        // var str = route.component
        var str = route.component.length > 0 ? route.component : "/Home"

        // 动态加载路由
        let fmtRoute = {
            path: route.path,
            component: (resolve) => require(['@/views' + str + '.vue'], resolve),
            name: route.name,
            title: route.title,
            icon: route.icon,
            hidden: route.hidden,
            children: route.children
        }

        fmtRoutes.push(fmtRoute)

    })
    return fmtRoutes
}